import axios from 'axios'
import { useStore} from '@/stores'
import { ElMessage } from 'element-plus'
import router from '@/router'
const baseURL = 'http://big-event-vue-api-t.itheima.net'

const instance = axios.create({
  // TODO 1. 基础地址，超时时间
  baseURL,
  timeout: 5000
})

//请求拦截器,携带token
instance.interceptors.request.use(
  (config) => {
    // TODO 2. 携带token
    const store = useStore()
    if (store.token) {
      console.log('请求携带token', store.token)
      config.headers.Authorization = store.token
    }
    return config
  },
  (err) => Promise.reject(err)
)

//响应拦截器
instance.interceptors.response.use(
  (res) => {
    // TODO 3. 处理业务失败
    if (res.data.code === 0) {
      return res
    }else{
      ElMessage.error(res.data.message || '业务失败')
      return Promise.reject(new Error(res.data.message))
    }
    // TODO 4. 摘取核心响应数据
  },

  
  (err) => {
    // TODO 5. 处理401错误
    if (err.response.status === 401) {
      ElMessage.error('登录已过期，请重新登录')
      router.push('/login')
    }

    // TODO 6. 处理其它错误
    ElMessage.error(err.response.data.message || '业务失败')
    return Promise.reject(err)
  }
)

export default instance
export { baseURL }
